import React, { useEffect, useState, memo } from 'react'
import { Column, G2 } from '@antv/g2plot'
import { ipList as presentIp } from '../../ipConfig'

function PercentageOfHotelData({ selectedTags, timeDate }) {
  const [data, setData] = useState(null)
  const [hotellistId, setHotellistId] = useState(null)

  G2.registerInteraction('element-link', {
    start: [
      { trigger: 'interval:mouseenter', action: 'element-link-by-color:link' },
    ],
    end: [
      {
        trigger: 'interval:mouseleave',
        action: 'element-link-by-color:unlink',
      },
    ],
  })

  useEffect(() => {
    fetch(
      `${presentIp.DEV_IP}/hotel_data_proportion?hotellist=${hotellistId}&leftTime=${timeDate[0]}&rightTime=${timeDate[1]}`,
      {
        headers: {
          token: sessionStorage.getItem('token'),
        },
      }
    )
      .then((data) => data.json())
      .then((json) => {
        setData(json.data)
      })
  }, [hotellistId, timeDate])

  useEffect(() => {
    const hotellistId = []
    selectedTags.map((item) => {
      hotellistId.push(item.hotelId)
      return item
    })
    if (hotellistId.length === 0) {
      hotellistId.push(-1)
    }
    setHotellistId(hotellistId)
  }, [selectedTags])

  useEffect(() => {
    if (data) {
      document.getElementById('percentageOfHotelData').innerHTML = ''
      draw(data)
    }
  }, [data])

  const draw = () => {
    const columnPlot = new Column('percentageOfHotelData', {
      data,
      xField: 'property',
      yField: 'value',
      seriesField: 'hotelName',
      isPercent: true,
      isStack: true,
      meta: {
        value: {
          min: 0,
          max: 1,
        },
      },
      label: {
        position: 'middle',
        content: (item) => {
          return `${(item.value * 100).toFixed(2)}%`
        },
        style: {
          fill: '#fff',
        },
      },
      tooltip: false,
      interactions: [
        { type: 'element-highlight-by-color' },
        { type: 'element-link' },
      ],
    })

    columnPlot.render()
  }

  return (
    <>
      <div
        id="percentageOfHotelData"
        style={{ height: '100%', width: '100%', padding: '20px' }}></div>
    </>
  )
}

export default memo(PercentageOfHotelData)
